const acorn = require('acorn');
const jsx = require('acorn-jsx');
const https = require('https');
const fs = require('fs');
const path = require('path');

// 配置acorn以支持JSX和其他扩展
const parser = acorn.Parser.extend(jsx());

// ES6特性列表
const es6Features = new Set([
    'ArrowFunctionExpression',
    'TemplateLiteral',
    'VariableDeclaration', // 检查 `kind` 为 'let' 或 'const'
    'ClassDeclaration',
    'ClassExpression',
    'ImportDeclaration',
    'ExportNamedDeclaration',
    'ExportDefaultDeclaration',
    'ForOfStatement',
    'SpreadElement',
    'RestElement',
    'DestructuringPattern',
    'MethodDefinition',
    'Super',
    'ComputedProperty',
    'GeneratorFunction',
    'YieldExpression',
    'AsyncFunction',
    'AwaitExpression',
    'ObjectPattern',
    'ArrayPattern',
    'TaggedTemplateExpression',
    'MetaProperty',
    'NewExpression', // 检测 Promise
    'CallExpression', // 检测 Promise
    'ImportSpecifier',
    'ExportSpecifier',
    'ExperimentalRestProperty',
    'ExperimentalSpreadProperty',
    'OptionalChaining',
    'NullishCoalescingOperator',
    'StaticBlock'
]);

// 抓取 JS 代码
function fetchJS(url) {
    return new Promise((resolve, reject) => {
        https.get(url, (res) => {
            let data = '';
            res.on('data', (chunk) => data += chunk);
            res.on('end', () => resolve(data));
        }).on('error', reject);
    });
}

// 检测ES6特性
function detectES6Features(ast) {
    const detectedFeatures = new Set();
    function traverse(node) {
        if (es6Features.has(node.type)) {
            if (node.type === 'VariableDeclaration' && ['let', 'const'].includes(node.kind)) {
                detectedFeatures.add(`VariableDeclaration (${node.kind})`);
            } else if (node.type === 'NewExpression' || node.type === 'CallExpression') {
                if (node.callee.type === 'Identifier' && node.callee.name === 'Promise') {
                    detectedFeatures.add('Promise');
                } else if (node.callee.type === 'MemberExpression' && node.callee.object.name === 'Promise') {
                    detectedFeatures.add('Promise');
                }
            } else if (node.type === 'Super') {
                detectedFeatures.add('Super');
            } else if (node.type === 'OptionalChaining') {
                detectedFeatures.add('OptionalChaining');
            } else if (node.type === 'NullishCoalescingOperator') {
                detectedFeatures.add('NullishCoalescingOperator');
            } else if (node.type === 'StaticBlock') {
                detectedFeatures.add('StaticBlock');
            } else {
                detectedFeatures.add(node.type);
            }
        }
        for (const key in node) {
            if (node[key] && typeof node[key] === 'object') {
                traverse(node[key]);
            }
        }
    }
    traverse(ast);
    return detectedFeatures;
}

// 读取txt文件中的URL列表
function readUrlsFromTxt(filePath) {
    const urls = fs.readFileSync(filePath, 'utf-8').split('\n').map(url => url.trim()).filter(url => url);
    return urls;
}

// 写入txt文件
function writeUrlsToTxt(filePath, urls) {
    fs.writeFileSync(filePath, urls.join('\n'));
}

// 检查每个URL的ES6特性并分类
async function checkES6FeaturesInUrls(inputFilePath) {
    try {
        const urls = readUrlsFromTxt(inputFilePath);
        const hasES6Features = [];
        const noES6Features = [];

        for (const url of urls) {
            try {
                const response = await fetchJS(url);
                const ast = parser.parse(response, {
                    ecmaVersion: 2020,
                    sourceType: 'module'
                });
                const features = detectES6Features(ast);
                if (features.size > 0) {
                    hasES6Features.push(url);
                } else {
                    noES6Features.push(url);
                }
            } catch (error) {
                console.error(`Error processing URL ${url}:`, error);
                noES6Features.push(url); // 如果发生错误，假设没有ES6特性
            }
        }

        // 写入结果到文件
        const es6FilePath = 'es6_urls.txt';
        const noEs6FilePath = 'no_es6_urls.txt';
        writeUrlsToTxt(es6FilePath, hasES6Features);
        writeUrlsToTxt(noEs6FilePath, noES6Features);

        console.log('Processing complete. Results written to es6_urls.txt and no_es6_urls.txt.');
    } catch (error) {
        console.error('Error:', error);
    }
}

// 使用示例
const INPUT_TXT_FILE_PATH = 'es6/first_column.txt';
checkES6FeaturesInUrls(INPUT_TXT_FILE_PATH);
